package com.esreport.logstash.tracker;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author xuweiwei
 * @date 2018/12/25
 */
@Slf4j
public class LogFile {
    private File file;
    private RandomAccessFile access;
    private long lastModified;
    ReentrantLock reentrantLock;

    public LogFile(File file) throws FileNotFoundException {
        this.file = file;
        this.access = new RandomAccessFile(file, "r");
        this.lastModified = file.lastModified();
        reentrantLock = new ReentrantLock();
    }

    public boolean exist() {
        return file.exists();
    }

    public void lock() {
        reentrantLock.lock();
    }

    public boolean isLocked(){
        return reentrantLock.isLocked();
    }

    public void unLock() {
        reentrantLock.unlock();
    }

    public long length() {
        return file.length();
    }

    public long getLastModified() {
        return lastModified;
    }

    public void setLastModified(long lastModified) {
        this.lastModified = lastModified;
    }

    public void destroy() {
        try {
            access.close();
        } catch (IOException e) {
            log.error("关闭文件异常,文件:{}", file.getAbsolutePath(), e);
        }
    }

    public RandomAccessFile getAccess() {
        return access;
    }

    public File getFile() {
        return file;
    }

    public long getFilePoint() throws IOException {
        return access.getFilePointer();
    }

    public void reopen() throws FileNotFoundException {
        destroy();
        this.access = new RandomAccessFile(file, "r");

    }
}
